package com.gztms.usermgnt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gztms.enums.AppCodeEnum;
import com.gztms.enums.Gender;
import com.gztms.usermgnt.mapper.RoleMapper;
import com.gztms.usermgnt.mapper.UserMapper;
import com.gztms.usermgnt.pojo.RoleCode;
import com.gztms.usermgnt.pojo.User;
import com.gztms.usermgnt.pojo.vo.PasswordVO;
import com.gztms.usermgnt.pojo.vo.UserVO;
import com.gztms.usermgnt.service.UserService;
import com.gztms.utils.BeanCopyUtils;
import com.gztms.utils.ResultUtil;
import com.gztms.utils.SecurityUtils;
import com.gztms.utils.ValidateUtil;
import javafx.beans.binding.ObjectExpression;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author Zoey
 * @date 2023/3/8 1:04
 * @Description
 **/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public ResultUtil register(User user) {
        // 1、查询账号是否已经存在
        user.setUid(user.getPhone());
        User isExistUser = userMapper.selectById(user.getUid());
        if (ValidateUtil.isEmpty(user.getUsername())) {
            return new ResultUtil(ResultUtil.USER_INFO_NULL,"用户名为空");
        }else if (Objects.nonNull(isExistUser)){
            return new ResultUtil(ResultUtil.USER_EXISTED, "该账号已经注册");
        }else if (!ValidateUtil.checkPhoneNumber(user.getPhone())){
            return new ResultUtil(AppCodeEnum.PHONE_ERROR.getCode(), "请输入正确手机号格式");
        }
//        else if (! ValidateUtil.checkEmail(user.getEmail())){
//            return new ResultUtil(400,"请输入正确的邮箱格式");
//        }
        else if (!ValidateUtil.checkPassword(user.getPassword())){
            return new ResultUtil(400,"密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线！");
        }else {
            // 密码加密
            String password = passwordEncoder.encode(user.getPassword());
            user.setPassword(password);
            //  设置默认头像


            userMapper.insert(user);
            // 添加用户权限
            roleMapper.addRoleByUid(user.getUid(), RoleCode.ROLE_USER);
            return new ResultUtil(ResultUtil.SUCCESS,"用户注册成功");

        }
    }

    @Override
    public ResultUtil updateAvatar(String uid, String avatar) {
        User user = new User();
        user.setUid(uid);
        user.setAvatar(avatar);
        int res = userMapper.updateById(user);
        if (res == 1)  {
            return new ResultUtil(ResultUtil.SUCCESS, "头像修改成功");
        }
        return new ResultUtil(ResultUtil.SERVER_ERROR, "头像修改失败");
    }

    @Override
    public ResultUtil updateUserInfo(User user) {
        // 检验手机号是否正确

        if (!ValidateUtil.checkPhoneNumber(user.getPhone())) {
            return ResultUtil.errorResult(AppCodeEnum.PHONE_ERROR,AppCodeEnum.PHONE_ERROR.getMsg());
        } else if (!ValidateUtil.checkEmail(user.getEmail())) {
            return ResultUtil.errorResult(AppCodeEnum.EMAIL_ERROR,AppCodeEnum.EMAIL_ERROR.getMsg());
        }
        // 检验邮箱是否正确
        boolean flag = updateById(user);
        if (flag) {
            return ResultUtil.okResult();
        }
        return  ResultUtil.errorResult(AppCodeEnum.SYSTEM_ERROR);

    }

    @Override
    public ResultUtil getUserInfoByUid(String uid) {
        User user = getById(uid);
        if (Objects.isNull(user)) {
            return ResultUtil.errorResult(AppCodeEnum.SYSTEM_ERROR,"用户不存在");
        }
        UserVO userVO = BeanCopyUtils.copyBean(user, UserVO.class);
        // 设置性别
        if (userVO.getGender()== Gender.MALE) {
            userVO.setGenderName("男");
        }else if(userVO.getGender() == Gender.FEMALE) {
            userVO.setGenderName("女");
        }else {
            userVO.setGenderName("未知");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("user",user);
        log.info("user: ", userVO);
        return ResultUtil.okResult(map);
        // 过滤特殊字段password
//        QueryWrapper<User> wrapper = new QueryWrapper();
//        wrapper.select(User.class, info -> !info.getColumn().equals("password"));
//        User user = userMapper.selectById(uid);
//        if (Objects.isNull(user)){
//            return new ResultUtil(ResultUtil.SUCCESS, "用户不存在");
//        }
//        Map<String,User> map = new HashMap<>();
//        map.put("user", user);
//        return new ResultUtil(ResultUtil.SUCCESS,"用户个人信息查询成功", map);
    }


    @Override
    public ResultUtil addAdmin(User user) {
        // 1、检验改手机号是否已经征用、手机、邮箱格式
        user.setUid(user.getPhone());
        if (ValidateUtil.isEmpty(user.getUsername())) {
            return ResultUtil.errorResult(AppCodeEnum.USER_INFO_NULL,"用户名不能为空");
        }
        User isExistUser = getById(user.getUid());
        if (Objects.nonNull(isExistUser)) {
            return ResultUtil.errorResult(AppCodeEnum.USER_EXISTED,AppCodeEnum.USER_EXISTED.getMsg());
        }

        if (!ValidateUtil.checkPhoneNumber(user.getPhone())) {
            return ResultUtil.errorResult(AppCodeEnum.PHONE_ERROR,AppCodeEnum.PHONE_ERROR.getMsg());
        }else if (!ValidateUtil.checkEmail(user.getEmail())) {
            return ResultUtil.errorResult(AppCodeEnum.EMAIL_ERROR,AppCodeEnum.EMAIL_ERROR.getMsg());
        }

        // 设置默认密码
        user.setPassword("123456zy");
        String password = passwordEncoder.encode(user.getPassword());
        user.setPassword(password);
        boolean save = save(user);
        roleMapper.addRoleByUid(user.getUid(), RoleCode.ROLE_ADMIN);

        if (save) {
            return ResultUtil.okResult();
        }
        return ResultUtil.errorResult(AppCodeEnum.SYSTEM_ERROR);
    }

    @Override
    public ResultUtil updatePassword(PasswordVO passwordVO) {
        if (!ValidateUtil.checkPassword(passwordVO.getPassword())) {
            return ResultUtil.errorResult(AppCodeEnum.PASSWORD_ERROR,"长度在6~18之间，必须包含字母和数字");
        } else if (!passwordVO.getPassword().trim().equals(passwordVO.getCheckedPassword().trim())) {
            return ResultUtil.errorResult(AppCodeEnum.PASSWORD_ERROR,"两次密码不一致");
        }
        // 从springSecurity中获取uid
        String uid = SecurityUtils.getUid();
        User user = new User();
        // 加密
        String password = passwordEncoder.encode(passwordVO.getCheckedPassword());

        user.setUid(uid);
        user.setPassword(password);
        boolean update = updateById(user);
        if (update) {
            return ResultUtil.okResult(AppCodeEnum.SUCCESS.getCode(),"修改成功");
        }

        return ResultUtil.errorResult(AppCodeEnum.SYSTEM_ERROR);
    }
}
